package com.juxing.webserver.action.live;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.juxing.sdk.util.StringUtil;
import com.juxing.service.configCenter.bean.ActivityBean;
import com.juxing.service.configCenter.bean.ScenceBean;
import com.juxing.service.liveCenter.ILiveCenterService;
import com.juxing.service.liveCenter.bean.LiveBean;
import com.juxing.service.liveCenter.bean.LiveConstants;
import com.juxing.service.liveCenter.bean.LiveIndexBean;
import com.juxing.service.liveCenter.bean.LiveStreamBean;
import com.juxing.service.userCenter.IUserCenterService;
import com.juxing.service.userCenter.bean.UserBean;
import com.juxing.webserver.action.BaseAction;
import com.juxing.webserver.common.ReturnCodeConstant;

/**
 * 直播中心
 * @author brochen
 * @mail mongibello@163.com
 * @created 2016年2月2日
 *
 */
@Controller
@RequestMapping("live")
public class LiveAction extends BaseAction {

	private Logger logger = LoggerFactory.getLogger(LiveAction.class);
	
	@Autowired
	private ILiveCenterService liveCenterService;
	@Autowired
	private IUserCenterService userCenterService;
	
	/**
	 * 获取推流信息
	 * @param request
	 * @param response
	 * @param userId
	 * @return
	 */
	@RequestMapping("getPublishStream.json")
	public ModelAndView start(HttpServletRequest request, HttpServletResponse response
			,@RequestParam int userId		//用户ID
			) {
		
		LiveStreamBean streamBean = liveCenterService.generateStream(userId);
		if(streamBean == null) {
			return this.initErrorView(ReturnCodeConstant.SERVER_ERROR);
		}
		
		ModelAndView view = this.initSuccessView("live/getPublishStream");
		view.addObject("liveStreamId", streamBean.getId());
		JSONObject streamObj = JSONObject.parseObject(streamBean.getStream());
		view.addObject("stream", streamObj);
		
		return this.encryptedView(request, response, view);
	}
			
	@RequestMapping("start.json")
	public ModelAndView start(HttpServletRequest request, HttpServletResponse response
			,@RequestParam int userId							//用户ID
			,@RequestParam int liveStreamId						//直播流ID
			,@RequestParam String title							//直播主题
			,@RequestParam(required=false) int scenceId		//直播场景
			,@RequestParam(required=false) int activityId		//直播场景
			,@RequestParam(required=false) int cityId			//直播所在城市
			,@RequestParam(required=false) double lon			//直播所在经度
			,@RequestParam(required=false) double lat			//直播所在纬度
			) {
		//参数校验
		if(StringUtil.isEmpty(title)) {
			return this.initErrorView(ReturnCodeConstant.PARAM_ERROR);
		}
		long currTime = System.currentTimeMillis();
		LiveBean liveBean = new LiveBean();
		liveBean.setUserId(userId);
		liveBean.setStreamId(liveStreamId);
		liveBean.setTitle(title);
		liveBean.setScenceId(scenceId);
		liveBean.setActivityId(activityId);
		liveBean.setStartTime(currTime);
		liveBean.setCityId(cityId);
		liveBean.setLongtitude(lon);
		liveBean.setLatitude(lat);
		
		liveBean = liveCenterService.startLive(liveBean);
		if(liveBean == null) {
			//创建直播失败
			return this.initErrorView(ReturnCodeConstant.SERVER_ERROR);
		}
		
		//创建成功
		ModelAndView view = this.initSuccessView("live/start");
		view.addObject("liveBean", liveBean);
		view.addObject("praisePushInterval", LiveConstants.PRAISE_INTERVAL);
		view.addObject("queryLastestInfoInterval", LiveConstants.QUERY_LATEST_INTERVAL);
		
		return this.encryptedView(request, response, view);
	}
	
	@RequestMapping("activityLiveList.json")
	public ModelAndView liveList(HttpServletRequest request, HttpServletResponse response
			,@RequestParam int activityId		//活动ID
			) {
		
		//TODO
		ActivityBean activityBean = new ActivityBean();
		activityBean.setId(activityId);
		activityBean.setName("测试活动" + activityId);
		activityBean.setStartTime(System.currentTimeMillis() - 86400000);
		activityBean.setEndTime(System.currentTimeMillis() + 86400000);
		activityBean.setBgUrl("http://pic13.nipic.com/20110415/1347158_132411659346_2.jpg");
		activityBean.setType(1);
		activityBean.setH5Url("");
		
		ModelAndView view = this.initSuccessView("live/activityLiveList");
		view.addObject("activity", activityBean);
		List<LiveBean> liveList = liveCenterService.queryActivityLiveList(activityId);
		List<Map<String, Object>> liveMapList = new ArrayList<Map<String, Object>>();
		int liveCnt = 0;
		if(liveList != null) {
			liveCnt = liveList.size();
			for(LiveBean live : liveList) {
				Map<String, Object> row = new HashMap<String, Object>();
				row.put("id", live.getId());
				row.put("snapshotUrl", "http://img4.3lian.com/sucai/img6/230/29.jpg");//TODO
				UserBean hostUser = userCenterService.queryByUserId(live.getUserId());
				row.put("title", live.getTitle());
				row.put("hostUser", hostUser);
				ScenceBean scenceBean = new ScenceBean();
				scenceBean.setId(live.getScenceId());
				scenceBean.setName("场景" + live.getScenceId());
				scenceBean.setBgUrl("http://img3.redocn.com/20101213/20101211_0e830c2124ac3d92718fXrUdsYf49nDl.jpg");
				row.put("scence", scenceBean);
				LiveIndexBean liveIndex = new LiveIndexBean();//TODO
				liveIndex.setViewUser(1);
				liveIndex.setViewCnt(2);
				liveIndex.setPraise(3);
				row.put("index", liveIndex);
				
				row.put("type", 1);//TODO
				
				liveMapList.add(row);
			}
		}
		view.addObject("liveList", liveMapList);
		view.addObject("liveCnt", liveCnt);
		
		return this.encryptedView(request, response, view);
	}
	/**
	 * 加入直播
	 * @param request
	 * @param response
	 * @param activityId
	 * @return
	 */
	@RequestMapping("join.json")
	public ModelAndView join(HttpServletRequest request, HttpServletResponse response
			,@RequestParam int liveId		//活动ID
			) {
		
		LiveBean live = liveCenterService.queryLiveBean(liveId);
		if(live == null) {
			return this.initErrorView(ReturnCodeConstant.PARAM_ERROR);
		}
		Map<String, Object> row = new HashMap<String, Object>();
		row.put("id", live.getId());
		row.put("snapshotUrl", "http://img4.3lian.com/sucai/img6/230/29.jpg");//TODO
		UserBean hostUser = userCenterService.queryByUserId(live.getUserId());
		row.put("title", live.getTitle());
		row.put("hostUser", hostUser);
		ScenceBean scenceBean = new ScenceBean();
		scenceBean.setId(live.getScenceId());
		scenceBean.setName("场景" + live.getScenceId());
		scenceBean.setBgUrl("http://img3.redocn.com/20101213/20101211_0e830c2124ac3d92718fXrUdsYf49nDl.jpg");
		row.put("scence", scenceBean);
		LiveIndexBean liveIndex = new LiveIndexBean();//TODO
		liveIndex.setViewUser(1);
		liveIndex.setViewCnt(2);
		liveIndex.setPraise(3);
		row.put("index", liveIndex);
		row.put("status", 1);//TODO
		
		LiveStreamBean streamBean = liveCenterService.queryLiveStreamBean(live.getStreamId());
		JSONObject streamObj = JSONObject.parseObject(streamBean.getStream());
		row.put("stream", streamObj);
		ModelAndView view = this.initSuccessView("live/join");
		view.addObject("live", row);
		view.addObject("praisePushInterval", LiveConstants.PRAISE_INTERVAL);
		view.addObject("queryLastestInfoInterval", LiveConstants.QUERY_LATEST_INTERVAL);
		
		return this.encryptedView(request, response, view);
	}
	
	/**
	 * 用户离开直播
	 * @param request
	 * @param response
	 * @param liveId
	 * @return
	 */
	@RequestMapping("leave.json")
	public ModelAndView leave(HttpServletRequest request, HttpServletResponse response
			,@RequestParam int userId		//用户ID
			,@RequestParam int liveId		//直播ID
			) {
		
		return this.initSuccessView();
	}
	
	/**
	 * 点赞
	 * @param request
	 * @param response
	 * @param userId
	 * @param liveId
	 * @param praises
	 * @return
	 */
	@RequestMapping("clickPraises.json")
	public ModelAndView clickPraises(HttpServletRequest request, HttpServletResponse response
			,@RequestParam int userId		//用户ID
			,@RequestParam int liveId		//直播ID
			,@RequestParam int praises		//点赞数
			) {
		
		ModelAndView view = this.initSuccessView("live/clickPraises");
		view.addObject("totalPraises", 100);
		
		return this.encryptedView(request, response, view);
	}
	
	/**
	 * 获取直播最新信息
	 * @param request
	 * @param response
	 * @param userId
	 * @param liveId
	 * @param lastTimestamp
	 * @return
	 */
	@RequestMapping("queryLiveLatestInfo.json")
	public ModelAndView queryLiveLatestInfo(HttpServletRequest request, HttpServletResponse response
			,@RequestParam int userId		//用户ID
			,@RequestParam int liveId		//直播ID
			,@RequestParam long lastTimestamp  //上一次拉取的时间
			) {
		ModelAndView view = this.initSuccessView("live/queryLiveLatestInfo");
		view.addObject("status", "1");
		view.addObject("timestamp", System.currentTimeMillis());
		view.addObject("totalPraises", 100);
		view.addObject("totalViewUser", 200);
		List<Map<String, Object>> viewUsers = new ArrayList<Map<String, Object>>();
		for(int i = 0; i < 10; i++) {
			Map<String, Object> viewUser = new HashMap<String, Object>();
			viewUsers.add(viewUser);
			viewUser.put("userId", i+1);
			viewUser.put("nickname", "昵称" + (i + 1));
			viewUser.put("headUrl", "http://img3.redocn.com/20101213/20101211_0e830c2124ac3d92718fXrUdsYf49nDl.jpg");
		}
		view.addObject("viewUsers", viewUsers);
		
		
		return this.encryptedView(request, response, view);
	}
	
}
